using System;
using System.IO;
using System.Text.RegularExpressions;

using ObjectRelationalMapping.Helper;

namespace ObjectRelationalMapping
{
    internal static partial class Output
    {
        public static void Write ( )
        {
            CreateDirectory ();
            WriteCommonFiles ();
        }

        private static void CreateDirectory ( )
        {
            if ( !Directory.Exists ( 
                Common.ProjectDirectoryForClassObjects ) )
            {
                Directory.CreateDirectory ( 
                    Common.ProjectDirectoryForClassObjects );
            }
            if ( !Directory.Exists ( 
                Common.ProjectDirectoryForDatabaseObjects ) )
            {
                Directory.CreateDirectory ( 
                    Common.ProjectDirectoryForDatabaseObjects );
            }
            if ( !Directory.Exists (
                Common.ProjectDirectoryForHelperObjects ) )
            {
                Directory.CreateDirectory (
                    Common.ProjectDirectoryForHelperObjects );
            }
        }

        private static void WriteCommonFiles ( )
        {
            if ( Common.EntityCollection.Count > 0 )
            {
                Console.Write ( "Writing the helper files..." );

                string temporaryTemplateForEntityClassObject =
                    Regex.Replace (
                        Common.TemplateForEntityClassObject,
                        Common.Constants.UserDefinedApplicationNamespace,
                        Common.ApplicationNamespace );
                string temporaryTemplateForSqlHelperClassObject =
                    Regex.Replace (
                        Common.TemplateForSqlHelperClassObject,
                        Common.Constants.UserDefinedApplicationNamespace,
                        Common.ApplicationNamespace );

                string fileName;
                StreamWriter fileWriter;

                fileName = Common.ProjectDirectoryForHelperObjects + "Entity.cs";
                fileWriter = new StreamWriter ( fileName );
                fileWriter.WriteLine ( temporaryTemplateForEntityClassObject );
                fileWriter.Close ();

                fileName = Common.ProjectDirectoryForHelperObjects + "SqlHelper.cs";
                fileWriter = new StreamWriter ( fileName );
                fileWriter.WriteLine ( temporaryTemplateForSqlHelperClassObject );
                fileWriter.Close ();

                Console.WriteLine ( "and 2 helper files were written." );
            }
        }
    }
}
